//故障类型
import React, { Component } from 'react';
import { Table, Button, Form,Tabs ,notification ,Modal} from 'antd';
import '@/assets/css/settings';
import BasicDrawer from "../../../components_yyr/common/basicDrawer";
import { euqApplicationName } from '../../../config';
const { TabPane } = Tabs;
function openNotification(type, message) {
	notification.open({
		type: type,
		message: message,
		duration: 2,
	});
};
class App extends Component {
	state = {
		loading: false, //加载中...
		dataSource: [], //数据源
		drawerVisible: false,//新增修改抽屉的显示与隐藏
		chooseData: {},
		drawerTitle: '',
		total:0,
		formValues:{},
		cityData:[],
		mainFactoryList:[],
		selectedRows:[],
		drawerInitialValue:0,
		visible:false,
		selectedRowKeys:[]
	};
	componentDidMount() {
		this.fetch({
			pageNum: 1,
			pageSize: 10
		});
		// this.getInfo();
	}
	//初始化加载数据
	fetch = (data) => {
		this.setState({ loading: true })
		this.get(euqApplicationName + '/api/findEquFaultTypePageList').then(res => {
			console.log(res.data)
			this.setState({
				loading: false,
				dataSource: res.data,
				total:res.data.total,
				formValues:data
			});
		})
	}
	getInfo=()=>{
		this.post('/carrierPrice/mainFactoryList').then(res => this.setState({	mainFactoryList: res.data}))//主机厂
	}

	//表单查询
	filterSubmit = (values) => {
		values.pageNum = this.state.formValues.pageNum;
		values.pageSize = this.state.formValues.pageSize;
		this.fetch(values);
	};

	handleConfirm = (value, api,chooseData) => {
		if(api===1){
			this.get(`/airCargo/delAirCargo?id=${chooseData.id}`).then(res=>{
				this.success();
				this.fetch({...this.state.formValues});
			})
		}
		
	}

	formList = () => {
		const formList = [
			{				type: "TIMEFRAME", label: "计划时间", field: "factoryName",},
			{				type: "INPUT", label: "设备信息", field: "route" 	  },
		]
		return formList;
	};
	drawerFormList = (data,drawerInitialValue) => {
		const {mainFactoryList}=this.state;
		console.log(data)
		const drawerFormList = [
			{
				type: "INPUT",
				label: "故障类型名称",
				field: "name",
				initialValue: (drawerInitialValue == 1 ? data.name : ''),
				required:true
			},
			{
				type: "INPUT",
				label: "故障类型编码",
				field: "code",
				initialValue: (drawerInitialValue == 1 ? data.code : ''),
				required:false
			},
			
		];
		if(drawerInitialValue === 2 || drawerInitialValue === 0 ){
			let da = {
				type: 'CHECKBOXALONE',
				label: '使用自动编码',
				field: 'useAutoCode',
				initialValue: true,
				required: false,
			}
			drawerFormList.push(da)
		}
		return drawerFormList;
	};
	
	  // 提交modal
		handleSubmit = data => {
			let pdata = this.state.chooseData
			let drawerInitialValue = this.state.drawerInitialValue
			var arr = Object.keys(pdata);
			data.pid = 0
			if(arr.length !== 0){
				data.pid = pdata.pid 
			}; //true 为空， false 不为空
			if(drawerInitialValue === 1){
				data.id = pdata.id
			}
			let str = euqApplicationName + '/api/'
			if(drawerInitialValue === 0){
				str = str + 'addEquFaultType'
			} else if (drawerInitialValue === 1) {
				str = str + 'editEquFaultType'
			} else if (drawerInitialValue === 2) {
				str = str + 'addEquFaultTypeNext'
				data.id = pdata.id
			}
			console.log(str)
			this.post(str,{data}).then(res=>{
				this.success();
				this.fetch();
				this.onClose();
				this.setState({selectedRows:[],chooseData:{},drawerInitialValue:0,selectedRowKeys:[]})
			})
			
		};

			// 打开modal，判断是修改还是新增 0新增同级 1修改 2新增下级
		handleModal = (type,data ) => {
			let selectedRows = this.state.selectedRows
			console.log(selectedRows)
			if(type===0){
				if(selectedRows.length>1){
					openNotification('warning','请（仅）勾选一个节点')
					return
				}
				if(selectedRows.length === 1){
					this.setState({chooseData:selectedRows[0]})
				}
				this.setState({
					drawerTitle: "添加同级",
					drawerVisible: true,
					drawerInitialValue: 0,
				});
			} else if(type===1){
				if(selectedRows.length > 1 || selectedRows.length === 0){
					openNotification('warning','请（仅）勾选一个节点')
					return
				}
				this.setState({
					drawerTitle: "修改",
					drawerVisible: true,
					drawerInitialValue: 1,
					chooseData:selectedRows[0]
				});
			} else if(type===2){
				if(selectedRows.length > 1 || selectedRows.length === 0){
					openNotification('warning','请（仅）勾选一个节点')
					return
				}
				this.setState({
					drawerTitle: "添加下级",
					drawerVisible: true,
					drawerInitialValue: 2,
					chooseData:selectedRows[0]
				});
			}
			
		};

		deleteModal = () => {
			let selectedRows = this.state.selectedRows
			if(selectedRows.length === 0){
				openNotification('warning','请勾选节点')
				return
			}else{
				this.setState({visible:true})
			}

		}

		onClose=()=>{
			this.setState({
				drawerVisible: false,
				chooseData: {},
			});
			this.modalRef.props.form.resetFields();
		}

		handleOk = () => {
			let selectedRows = this.state.selectedRows
			let id = ''
			for(var item of selectedRows){
				id += item.id + ','
			}
			var tempStr = id.substring(0,id.length-1);
			console.log(tempStr)
			this.get(euqApplicationName + '/api/deleteEquFaultTypeList?ids=' + tempStr).then(res=>{
				this.success()
				this.fetch()
				this.setState({
					selectedRows:[],
					chooseData:{},
					selectedRowKeys:[]
				})
				this.handleCancel()
			})
		}

		handleCancel = () => {
			this.setState({
				visible:false,
			})
		}
	render() {
		const columns = [
			{
				title: '故障类别',
				// width:150,
				dataIndex: 'name',
			},
			{
				title: '故障类型编码',
				// width:100,
				dataIndex: 'code',
			},
			// {
			// 	title: '操作',
			// 	width:150,
			// 	render: (text, record) => {
			// 		return	<span>
			// 			{/* <a href onClick={()=>this.handleModal(1,record)}>详细</a>
			// 			<Divider type="vertical" /> */}
			// 			<a href onClick={()=>this.handleModal(1,record)}>添加</a>
			// 			{/* <Divider type="vertical" />
			// 			<BasicConfirm title='确认删除?'api={1} button={false} buttonName='删除' data={record}  handleConfirm={this.handleConfirm}/> */}
			// 		</span>
			// 	}
			// }
		];

		const {chooseData,drawerVisible,drawerTitle,dataSource,loading,total,formValues}=this.state;
	
		const drawerProps={
			onRef:(ref)=>this.modalRef=ref,visible:drawerVisible,width:700,drawerFormList:this.drawerFormList(chooseData,this.state.drawerInitialValue),
			submit:this.handleSubmit,onClose:this.onClose,title:drawerTitle
		}
		
		const rowSelection = {
			onChange: (selectedRowKeys, selectedRows) => {
			  console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
			  this.setState({selectedRows,selectedRowKeys})
			},
			onSelect: (record, selected, selectedRows) => {
			  console.log(record, selected, selectedRows);
			  this.setState({selectedRows})
			},
			onSelectAll: (selected, selectedRows, changeRows) => {
			  console.log(selected, selectedRows, changeRows);
			  this.setState({selectedRows})
			},
			selectedRowKeys : this.state.selectedRowKeys
		  };
		return (
			<div className="shadow-radius">
				{/* <Card><BasicForm formList={this.formList()} filterSubmit={this.filterSubmit} labelSpan={8} wrapperSpan={12} onRef={(ref) => this.child = ref} /></Card> */}
				
                <Tabs tabBarExtraContent={
                    <div className="buttonList">
					<Button icon="plus" onClick={()=>this.handleModal(0,{})} type="primary"> 添加同级</Button>
                    <Button icon="plus" onClick={()=>this.handleModal(2,{})} type="primary"> 添加下级</Button>
					<Button icon="edit" onClick={()=>this.handleModal(1,{})} type="primary"> 修改</Button>
					<Button icon="delete" onClick={()=>this.deleteModal(0,{})} type="primary"> 删除</Button>  
					{/* <Button icon="arrow-up" onClick={()=>this.handleModal(0,{})} type="primary"> 上移</Button>  
					<Button icon="arrow-down" onClick={()=>this.handleModal(0,{})} type="primary"> 下移</Button>   */}

					{/* <Button icon="form" onClick={()=>this.handleModal(0,{})} type="primary"> 执行计划</Button> */}
					{/* <Button icon="apartment" onClick={()=>this.handleModal(0,{})} type="primary"> 派工</Button> */}
					{/* <FileDown fileName='设备台账模板' buttonName='模板下载' apiPath='/airCargo/carrierPriceExcel'/> */}
					{/* <FileDown fileName='保养工单清单' buttonName='导出' method='post' apiPath='/airCargo/exportCarrierPriceDataExcel' data={formValues}/> */}
					{/* <FileUpload buttonName='导入' apiPath='/airCargo/carrierPriceExcel' load={true} fetch={()=>this.fetch({...formValues})}/> */}
				</div>
                }>
                    <TabPane tab='故障类型' key='1'>
						{dataSource && dataSource.length > 0 ?
                        <Table columns={columns} rowKey={(record, index) => record.id} dataSource={this.state.dataSource} pagination={false} rowSelection={rowSelection}	loading={loading}  defaultExpandAllRows={true}	/> : '暂无数据'}
                        {/* <Paging total={total} formValues={formValues} fetch={(pager)=>this.fetch(pager)}/> scroll={{y:500,x:1300}}*/}
                    </TabPane>
                </Tabs>
				 
				<BasicDrawer	{...drawerProps} />

				<Modal
					title="提示"
					visible={this.state.visible}
					onOk={this.handleOk}
					onCancel={this.handleCancel}
					>
					<p>确认删除该项及其子项？</p>
				</Modal>
			</div>
		);
	}
}
export default Form.create()(App);